package com.jiawei.permission.aspect;

import com.jiawei.entity.pojo.Rt;
import com.jiawei.permission.PermissionCheck;
import com.jiawei.permission.annotation.Permission;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author : willian fu
 * @version : 1.0
 * 拦截被@Permission注解的方法
 */
@Slf4j
@Aspect
@Component
public class PermissionAspect {
    //开始时间
    private static ThreadLocal<Long> time = new ThreadLocal<>();

    @Autowired
    private PermissionCheck permissionCheck;
    /***
     * 定义controller切入点拦截，拦截被@Permission注解的方法
     */
    @Pointcut("@annotation(com.jiawei.permission.annotation.Permission)")
    public void permissionAspect() {}

    /**
     * 处理拦截的请求，判断是否具有访问权
     * @param joinPoint
     */
    @Around(value = "permissionAspect() && @annotation(value)")
    public Object judgePermission(ProceedingJoinPoint joinPoint, Permission value) throws Throwable {
        time.set(System.currentTimeMillis());
        Object proceed = null;
        if (permissionCheck.verify(value.value())) {
            //权限校验通过，允许执行
            proceed = joinPoint.proceed();
            log.info("访问{}成功，耗时 {}ms", value.value(), System.currentTimeMillis() - time.get());
        }else {
            proceed = Rt.noAuthority("无权访问，有需要请联系管理员");
            log.warn("访问{}被拒绝，耗时 {}ms", value.value(), System.currentTimeMillis() - time.get());
        }
        return proceed;
    }

}
